//function to validate input of registry account
var formValidate = function() {
	// creating the data object to be sent to backend
	$("#usernamesignuperror").css("display", "none");
	$("#emailsignuperror").css('display', 'none');
	var formdata = new FormData();
	var phone = $("#usernamesignup").val();
	var errorFlag = false;
	if (!isPhoneNumber(phone)) {
		$('#usernamesignuperror').text('Invalid Phone');
		$("#usernamesignuperror").css("display", "block");
		errorFlag = true;
	} else {

			$("#usernamesignuperror").css('display', 'none');
	}
	// email
	var email = $("#emailsignup").val();
	if (!isEmail(email)) {
		$('#emailsignuperror').text('Invalid Email');
		$("#emailsignuperror").css("display", "block");

		errorFlag = true;
	} else {
			$("#emailsignuperror").css('display', 'none');
	}
	// password
	var password = $("#passwordsignup").val();
	if (password == "" || password.length < 6) {
		$("#passwordsignuperror").css("display", "block");

		errorFlag = true;
	} else {
		formdata.append('passwordsignup', CryptoJS.MD5(password));
		$("#passwordsignuperror").css('display', 'none');
	}
	var password_confirm = $("#passwordsignup_confirm").val();
	if (password_confirm != password) {
		$("#passwordsignup_confirmerror").css("display", "block");
		// data[data.length]=new
		// param('passwordsignup_confirm',CryptoJS.MD5(password_confirm));
		errorFlag = true;
	} else {
		$("#passwordsignup_confirmerror").css('display', 'none');
	}

	if (errorFlag) {
		return;
	} else {
		//check phone and email if exist 
		checkAccount(phone, email);
	}
}

// function to get the data by setting url, filter, success function and error
// function
var checkAccount = function(phone, email) {
	// making the ajax call
	var formdata = new FormData();
	formdata.append('phone', phone);
	formdata.append('email', email);
	var xhr = new XMLHttpRequest();       

    xhr.open("GET","/login?action=checkaccount&phone="+phone+"&email="+email, true);

    xhr.send(formdata);

    xhr.onload = function(e) {

        if (this.status == 200) {
        	var data = $.parseJSON(this.responseText).data;
        	if (data.length > 0) {
				for ( var int = 0; int < data.length; int++) {
					if (data[int].phone == $("#usernamesignup").val()) {
						$('#usernamesignuperror').text('Phone is already existed!');
						$("#usernamesignuperror").css("display", "block");
					}
					if (data[int].email == $("#emailsignup").val()) {
						$('#emailsignuperror').text('Email is already existed!');
						$("#emailsignuperror").css('display', 'block');
					}
				}
			} else {
				// register account after validating
				register();
			}
        	
        }
    }; 
}

// determine input is phone number
var isPhoneNumber = function(input) {
	var phoneRe = /^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/;
	var digits = input.replace(/\D/g, "");
	return (digits.match(phoneRe) !== null);
}

// determine input is phone number
var isEmail = function(input) {
	var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
	if (input == '' || !emailReg.test(input)) {
		return false;
	}
	return true;
}

//function to register user
var register = function() {
	var formdata = new FormData();
	var phone = $("#usernamesignup").val();
	var email = $("#emailsignup").val();
	var password = CryptoJS.MD5($("#passwordsignup").val());
	var xhr = new XMLHttpRequest();       

    xhr.open("POST","/login?action=PUT&phone="+phone+"&email="+email+"&password="+password, true);

    xhr.onload = function(e) {

        if (this.status == 200) {
        	document.location.href = '/default.html#tosuccess';
        } else {
        	alert("Error! please try it again");
        }
    }; 
    
    xhr.send(formdata);
}

//login system
var login = function() {
	var formdata = new FormData();
	var phone = $("#username").val();
	var password = CryptoJS.MD5($("#password").val());
	var xhr = new XMLHttpRequest();       

    xhr.open("GET","/login?action=login&phone="+phone+"&password="+password, true);

    xhr.onload = function(e) {

        if (this.status == 200) {
        	var data = $.parseJSON(this.responseText).data;
        	if (data.length > 0) {
        		$.cookie('useraccount', $('#username').val(), { expires: 14 });
        		var remember = $('#loginkeeping').is(':checked');
        		if (remember == true) 
                {
                    var phone = $('#username').val();
                    var password = $('#password').val();

                    // set cookies to expire in 14 days
                    $.cookie('phone', phone, { expires: 14 });
                    $.cookie('password', password, { expires: 14 });
                    $.cookie('remember', true, { expires: 14 });
                                 
                }
                else
                {
                    // reset cookies
                    $.cookie('email', null);
                    $.cookie('password', null);
                    $.cookie('remember', false);
                }

        		document.location.href = '/map.html';
			} else {
				$("#loginstatus").css("display", "block");
				$.cookie('useraccount', '', { expires: 14 });
			}
        	
        } else {
        	alert("Error! please try it again");
        	$.cookie('useraccount', '', { expires: 14 });
        }
    }; 
    
    xhr.send(formdata);
}